/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PanelIndex.java
 *
 * Created on Nov 3, 2010, 5:36:37 PM
 */
package GUI;

import DBHandling.BillDetailHandling;
import DBHandling.BillHandling;
import DBHandling.DBUtil;
import DBHandling.ItemHandling;
import Entity.Account;
import Entity.Bill;
import Entity.Item;
import java.awt.Color;
import java.io.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.view.JasperViewer;

/**
 *
 * @author Vangnd
 */
public class ProduceBillsPanel extends javax.swing.JPanel {

    Account acc;
    Connection conn;
    DBUtil objDB;
    ResultSet rsUser;
    ResultSet rsBill;
    ResultSet rsItem;
    InputStream is = null;
    Map m = null;
    JasperPrint jp = null;
    DefaultTableModel model = null;
    DefaultComboBoxModel<String> itemModel;
    Boolean quantityError = true;
    private String loginUser;
    Bill bill;
    Item item;
    ItemHandling ih;
    BillHandling bh;
    BillDetailHandling bdh;
    String dateString;

    /**
     * Creates new form PanelIndex
     */
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public ProduceBillsPanel(String user) throws SQLException {
        initComponents();
        objDB = new DBUtil();
        conn = objDB.connect();
        loginUser = user;
        this.FillData();
        ih = new ItemHandling();
        //bill = new Bill(txtBillID.getText(), loginUser, dateString, txtCustomer.getText(), cbPayment.getSelectedItem().toString());


    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    private void FillData() throws SQLException {
        //get current date in String format
        Date d = new Date();
        Format fm = new SimpleDateFormat("MM/dd/YYYY");
        dateString = fm.format(d);
        //set date
        txtDate.setText(dateString);


        //set staff name:
        rsUser = objDB.executeSQL("Select fullname from Staffs where username='" + loginUser + "'");
        rsUser.last();
        String fullStaffName = rsUser.getString("fullname");
        txtFullname.setText(fullStaffName);

        //set billID
        rsBill = objDB.executeSQL("Select billID from bills");
        rsBill.last();
        int temp = rsBill.getRow() + 1;
        String billID = "BL" + String.valueOf(temp);
        txtBillID.setText(billID);


        //Fill item
        rsItem = objDB.executeSQL("Select itemName from Items order by itemName");
        itemModel = new DefaultComboBoxModel<String>();
        cbItemName.setModel(itemModel);
        itemModel.addElement("Select item...");
        while (rsItem.next()) {
            String tempItem = rsItem.getString("itemName");
            itemModel.addElement(tempItem);
        }


        model = new DefaultTableModel() {

            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        //add columns to table
        jTable1.setModel(model);
        model.addColumn("ItemID");
        model.addColumn("ItemName");
        model.addColumn("Unit");
        model.addColumn("Price");
        model.addColumn("Quantity");
        model.addColumn("returnable");
        model.addColumn("Item Total");
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //check whether required fields valid
    public boolean isValidated() {
        String customerName = txtCustomer.getText();
        String itemName = cbItemName.getSelectedItem().toString();
        String payment = cbPayment.getSelectedItem().toString();
        int quantity = Integer.parseInt(txtQuantity.getText());

        if ((customerName.trim().length() == 0) || ("Enter customer name...".equals(customerName))) {
            lblError.setText("Customer name cannot be empty");
            return false;
        } else if (quantity <= 0) {
            lblError.setText("Quantity must be a valid number");
            return false;
        } else if ("Select item...".equals(itemName)) {
            lblError.setText("Please select an item to add");
            return false;
        } else if ("Select payment method...".equals(payment)) {
            lblError.setText("Please select a payment method");
            return false;
        } else {
            return true;
        }
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //check if the items added to bill
    //return true if exist
    //false if not
    public boolean isExisted(String itemName) {
        String tempName;
        for (int i = 0; i < jTable1.getRowCount(); i++) {
            tempName = jTable1.getValueAt(i, 1).toString();
            if (tempName.equals(itemName)) {
                return true;
            }
        }
        return false;
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //method to add the exception to Exception.dat.
    //Exception raise when the quantiy input greater than the quantity inventory can supply
    //return true if successful
    //false if not
    public boolean addException(String billID, String itemID) throws ClassNotFoundException {

        try {
            //create a arraylist to contain old exception, load old exception by method readException();
            ArrayList<Vector> exArr = readException();//new ArrayList<Vector>();//
            
            //get current date
            Date d = new Date();
            Format fm = new SimpleDateFormat("MM/dd/YYYY");
            dateString = fm.format(d);
            
            //create stream to write to  file
            FileOutputStream fos = new FileOutputStream(new File(System.getProperty("user.dir"), "src\\Exception.dat"));
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            //get the Exception information (billid, itemid, date)
            Vector v = new Vector();
            v.add(billID);
            v.add(itemID);
            v.add(dateString);
            //add this exception to excception list
            exArr.add(v);
            //write the arraylist to file
            oos.writeObject(exArr);
            //close stream
            oos.close();
            fos.close();
            return true;
        } catch (FileNotFoundException ex) {
            return false;
        } catch (IOException ioEx) {
            return false;
        }
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //method to read data from file
    //return an arraylist contain exception information
    //return raw arraylist if cannot load old exception
    public ArrayList<Vector> readException() throws ClassNotFoundException {
        try {
            //open a stream to read from file
            FileInputStream fis = new FileInputStream(new File(System.getProperty("user.dir"), "src\\Exception.dat"));
            ObjectInputStream ois = new ObjectInputStream(fis);
            //read arraylist from file to temp
            ArrayList<Vector> temp = (ArrayList) ois.readObject();
            //close stream
            ois.close();
            fis.close();
            //return temp arraylist
            return temp;
        } catch (FileNotFoundException ex) {
            return new ArrayList<Vector>();
        } catch (IOException ioEx) {
            return new ArrayList<Vector>();
        }
    }
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //method to add item into bills
    public void addToBill() throws SQLException, FileNotFoundException, IOException, ClassNotFoundException {
        //get item information
        String itemName = cbItemName.getSelectedItem().toString();
        int quantity = Integer.parseInt(txtQuantity.getText());
        try {
            ResultSet rs = objDB.executeSQL("Select itemID, itemName, price, unit, status, returnable from Items where itemName ='" + itemName + "'");
            while (rs.next()) {
                Vector v = new Vector();
                v.add(rs.getString("itemID"));
                v.add(rs.getString("itemName"));
                v.add(rs.getString("unit"));
                v.add(rs.getString("price"));
                
                //check if the input quantity greater than item quantity in the inventory
                if ((Integer.parseInt(rs.getString("status")) < quantity)) {
                    quantity = Integer.parseInt(rs.getString("status"));
                    v.add(quantity);
                    //add exception to file
                    addException(txtBillID.getText(), rs.getString("itemID").toString());
                    lblError.setText("The item quantity less than required, just maximum quantity added!");
                } else {
                    //if not
                    v.add(quantity);
                }
                double price = Double.parseDouble(rs.getString("price"));
                double total = price * quantity;
                v.add(rs.getString("returnable"));
                v.add(total);
                //add item row to table
                model.addRow(v);
            }
        } catch (SQLException sqlEx) {
            JOptionPane.showMessageDialog(null, "Cannot find input item in the database, may be a database connection lost, please check out");
        }
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //method to preview bills
    public boolean preview() {
        try {
            //read bills template
            String rp = "Report.jasper";
            //pass parameter via hashmap()
            m = new HashMap();
            m.put("BillID", txtBillID.getText());
            is = this.getClass().getClassLoader().getResourceAsStream(rp);;
            jp = JasperFillManager.fillReport(is, m, conn);
            JasperViewer jv = new JasperViewer(jp);
            jv.removeWindowListener(jv.getWindowListeners()[0]);
            //set the bill visible
            jv.setVisible(true);
            return true;
        } catch (Exception ex) {
            return false;
        }
    }
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar7 = new javax.swing.JToolBar();
        jLabel13 = new javax.swing.JLabel();
        btnNew = new javax.swing.JButton();
        jLabel16 = new javax.swing.JLabel();
        jLabel21 = new javax.swing.JLabel();
        btnEdit = new javax.swing.JButton();
        jLabel20 = new javax.swing.JLabel();
        btnRemove = new javax.swing.JButton();
        jLabel17 = new javax.swing.JLabel();
        btnRemoveAll = new javax.swing.JButton();
        jLabel22 = new javax.swing.JLabel();
        btnProduce = new javax.swing.JButton();
        jLabel9 = new javax.swing.JLabel();
        jLabel18 = new javax.swing.JLabel();
        btnCancel = new javax.swing.JButton();
        jLabel19 = new javax.swing.JLabel();
        jLabel23 = new javax.swing.JLabel();
        btnHelp = new javax.swing.JButton();
        lblBanner = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        lblDate = new javax.swing.JLabel();
        txtDate = new javax.swing.JLabel();
        lblFullname = new javax.swing.JLabel();
        txtFullname = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtCustomer = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtBillID = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        cbPayment = new javax.swing.JComboBox();
        jSeparator1 = new javax.swing.JSeparator();
        cbItemName = new javax.swing.JComboBox();
        txtQuantity = new javax.swing.JTextField();
        btnAdd = new javax.swing.JButton();
        lblError = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setBackground(new java.awt.Color(255, 255, 255));
        setMinimumSize(new java.awt.Dimension(700, 300));
        setPreferredSize(new java.awt.Dimension(747, 591));
        setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jToolBar7.setBackground(new java.awt.Color(255, 255, 255));
        jToolBar7.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jToolBar7.setFloatable(false);
        jToolBar7.setRollover(true);
        jToolBar7.setEnabled(false);
        jToolBar7.setName("jToolBar7"); // NOI18N

        jLabel13.setText("         "); // NOI18N
        jLabel13.setToolTipText("");
        jLabel13.setName("jLabel13"); // NOI18N
        jToolBar7.add(jLabel13);

        btnNew.setBackground(new java.awt.Color(255, 255, 255));
        btnNew.setFont(new java.awt.Font("Tahoma", 1, 12));
        btnNew.setForeground(new java.awt.Color(0, 0, 204));
        btnNew.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/add_item_48.png"))); // NOI18N
        btnNew.setText("New Bill");
        btnNew.setFocusable(false);
        btnNew.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnNew.setName("btnNew"); // NOI18N
        btnNew.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewActionPerformed(evt);
            }
        });
        jToolBar7.add(btnNew);

        jLabel16.setName("jLabel16"); // NOI18N
        jToolBar7.add(jLabel16);

        jLabel21.setText("        ");
        jLabel21.setName("jLabel21"); // NOI18N
        jToolBar7.add(jLabel21);

        btnEdit.setBackground(new java.awt.Color(255, 255, 255));
        btnEdit.setFont(new java.awt.Font("Tahoma", 1, 12));
        btnEdit.setForeground(new java.awt.Color(0, 0, 204));
        btnEdit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/edit_item_48.png"))); // NOI18N
        btnEdit.setText("Edit selected");
        btnEdit.setFocusable(false);
        btnEdit.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnEdit.setName("btnEdit"); // NOI18N
        btnEdit.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditActionPerformed(evt);
            }
        });
        jToolBar7.add(btnEdit);

        jLabel20.setText("        ");
        jLabel20.setName("jLabel20"); // NOI18N
        jToolBar7.add(jLabel20);

        btnRemove.setBackground(new java.awt.Color(255, 255, 255));
        btnRemove.setFont(new java.awt.Font("Tahoma", 1, 12));
        btnRemove.setForeground(new java.awt.Color(0, 0, 204));
        btnRemove.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/delete_item_48.png"))); // NOI18N
        btnRemove.setText("Remove Selected");
        btnRemove.setFocusable(false);
        btnRemove.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnRemove.setName("btnRemove"); // NOI18N
        btnRemove.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveActionPerformed(evt);
            }
        });
        jToolBar7.add(btnRemove);

        jLabel17.setText("        ");
        jLabel17.setName("jLabel17"); // NOI18N
        jToolBar7.add(jLabel17);

        btnRemoveAll.setBackground(new java.awt.Color(255, 255, 255));
        btnRemoveAll.setFont(new java.awt.Font("Tahoma", 1, 12));
        btnRemoveAll.setForeground(new java.awt.Color(0, 0, 153));
        btnRemoveAll.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/left_arrow_48.png"))); // NOI18N
        btnRemoveAll.setText("Remove All");
        btnRemoveAll.setFocusable(false);
        btnRemoveAll.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnRemoveAll.setName("btnRemoveAll"); // NOI18N
        btnRemoveAll.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnRemoveAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveAllActionPerformed(evt);
            }
        });
        jToolBar7.add(btnRemoveAll);

        jLabel22.setText("        ");
        jLabel22.setName("jLabel22"); // NOI18N
        jToolBar7.add(jLabel22);

        btnProduce.setBackground(new java.awt.Color(255, 255, 255));
        btnProduce.setFont(new java.awt.Font("Tahoma", 1, 12));
        btnProduce.setForeground(new java.awt.Color(0, 0, 204));
        btnProduce.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/bill_accept_48.png"))); // NOI18N
        btnProduce.setText("Produce Bill");
        btnProduce.setFocusable(false);
        btnProduce.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnProduce.setName("btnProduce"); // NOI18N
        btnProduce.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnProduce.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnProduceActionPerformed(evt);
            }
        });
        jToolBar7.add(btnProduce);

        jLabel9.setText("   ");
        jLabel9.setName("jLabel9"); // NOI18N
        jToolBar7.add(jLabel9);

        jLabel18.setText("       ");
        jLabel18.setName("jLabel18"); // NOI18N
        jToolBar7.add(jLabel18);

        btnCancel.setBackground(new java.awt.Color(255, 255, 255));
        btnCancel.setFont(new java.awt.Font("Tahoma", 1, 12));
        btnCancel.setForeground(new java.awt.Color(0, 0, 204));
        btnCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/bill_delete_48.png"))); // NOI18N
        btnCancel.setText("Cancel curent bill");
        btnCancel.setFocusable(false);
        btnCancel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnCancel.setName("btnCancel"); // NOI18N
        btnCancel.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });
        btnCancel.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                btnCancelFocusLost(evt);
            }
        });
        jToolBar7.add(btnCancel);

        jLabel19.setText("  ");
        jLabel19.setName("jLabel19"); // NOI18N
        jToolBar7.add(jLabel19);

        jLabel23.setText("          ");
        jLabel23.setName("jLabel23"); // NOI18N
        jToolBar7.add(jLabel23);

        btnHelp.setBackground(new java.awt.Color(255, 255, 255));
        btnHelp.setFont(new java.awt.Font("Tahoma", 1, 12));
        btnHelp.setForeground(new java.awt.Color(0, 0, 204));
        btnHelp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/help icon 48.png"))); // NOI18N
        btnHelp.setText("   Help   ");
        btnHelp.setFocusable(false);
        btnHelp.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnHelp.setName("btnHelp"); // NOI18N
        btnHelp.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnHelp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnHelpActionPerformed(evt);
            }
        });
        jToolBar7.add(btnHelp);

        add(jToolBar7, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 590, 800, 90));

        lblBanner.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/banner2.jpg"))); // NOI18N
        lblBanner.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        lblBanner.setName("lblBanner"); // NOI18N
        add(lblBanner, new org.netbeans.lib.awtextra.AbsoluteConstraints(-10, 0, 1200, 100));

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Produce Bill Routine"));
        jPanel1.setName("jPanel1"); // NOI18N
        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        lblDate.setText("Date:");
        lblDate.setName("lblDate"); // NOI18N
        jPanel1.add(lblDate, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, 50, 20));

        txtDate.setFont(new java.awt.Font("Tahoma", 2, 12));
        txtDate.setName("txtDate"); // NOI18N
        jPanel1.add(txtDate, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 20, 170, 20));

        lblFullname.setText("Sales Staff:");
        lblFullname.setName("lblFullname"); // NOI18N
        jPanel1.add(lblFullname, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 50, 70, 20));

        txtFullname.setFont(new java.awt.Font("Tahoma", 1, 14));
        txtFullname.setForeground(new java.awt.Color(0, 0, 204));
        txtFullname.setName("txtFullname"); // NOI18N
        jPanel1.add(txtFullname, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 50, 350, 20));

        jLabel2.setText("Customer Name:");
        jLabel2.setName("jLabel2"); // NOI18N
        jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(500, 20, -1, -1));

        txtCustomer.setName("txtCustomer"); // NOI18N
        txtCustomer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCustomerActionPerformed(evt);
            }
        });
        txtCustomer.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtCustomerFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtCustomerFocusLost(evt);
            }
        });
        jPanel1.add(txtCustomer, new org.netbeans.lib.awtextra.AbsoluteConstraints(600, 20, 200, -1));
        txtCustomer.getAccessibleContext().setAccessibleName("");

        jLabel3.setText("Bill ID:");
        jLabel3.setName("jLabel3"); // NOI18N
        jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 20, -1, 20));

        txtBillID.setFont(new java.awt.Font("Courier New", 1, 24));
        txtBillID.setForeground(new java.awt.Color(255, 0, 0));
        txtBillID.setName("txtBillID"); // NOI18N
        jPanel1.add(txtBillID, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 20, 60, 20));

        jLabel6.setText("Item Name");
        jLabel6.setName("jLabel6"); // NOI18N
        jPanel1.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 100, -1, -1));

        jLabel7.setText("Quantity");
        jLabel7.setName("jLabel7"); // NOI18N
        jPanel1.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 100, -1, -1));

        jLabel8.setText("Payment Method:");
        jLabel8.setName("jLabel8"); // NOI18N
        jPanel1.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(500, 50, -1, -1));

        cbPayment.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Select payment method...", "Direct", "Credit transfer", "Other" }));
        cbPayment.setName("cbPayment"); // NOI18N
        jPanel1.add(cbPayment, new org.netbeans.lib.awtextra.AbsoluteConstraints(600, 50, 200, -1));

        jSeparator1.setName("jSeparator1"); // NOI18N
        jPanel1.add(jSeparator1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 90, 790, 10));

        cbItemName.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Select item..." }));
        cbItemName.setName("cbItemName"); // NOI18N
        jPanel1.add(cbItemName, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 120, 350, -1));

        txtQuantity.setText("0");
        txtQuantity.setName("txtQuantity"); // NOI18N
        txtQuantity.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtQuantityActionPerformed(evt);
            }
        });
        txtQuantity.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtQuantityFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtQuantityFocusLost(evt);
            }
        });
        jPanel1.add(txtQuantity, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 120, 300, -1));

        btnAdd.setText("Add to bill");
        btnAdd.setName("btnAdd"); // NOI18N
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });
        jPanel1.add(btnAdd, new org.netbeans.lib.awtextra.AbsoluteConstraints(710, 120, -1, -1));

        add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 120, 830, 160));

        lblError.setForeground(new java.awt.Color(255, 51, 0));
        lblError.setName("lblError"); // NOI18N
        add(lblError, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 290, 800, 20));

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jTable1.setName("jTable1"); // NOI18N
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jTable1MousePressed(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 320, 1000, 210));
    }// </editor-fold>//GEN-END:initComponents

    private void btnNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewActionPerformed
       //check null and call the panel
        try {
            InventoryManagement.callJPanel(new ProduceBillsPanel(loginUser));
        } catch (SQLException ex) {
            Logger.getLogger(ProduceBillsPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnNewActionPerformed

    private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
        //edit the selected item
        //check if there are items selected
        if (jTable1.getSelectedRow() > -1) {
            int quantity = Integer.parseInt(txtQuantity.getText());
            double price = Double.parseDouble((String) model.getValueAt(jTable1.getSelectedRow(), 3));
            double itemsPrice = quantity * price;
            //up date quantity
            model.setValueAt(quantity, jTable1.getSelectedRow(), 4);
            //update items price
            model.setValueAt(itemsPrice, jTable1.getSelectedRow(), 6);
        } else {
            lblError.setText("Please select row that you want to edit!!");
        }
    }//GEN-LAST:event_btnEditActionPerformed

    private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveActionPerformed
//
        //remove selected items
        try {
            //check if there are items selected
            if (jTable1.getSelectedRow() > -1) {
                while (jTable1.getSelectedRows().length > 0) {
                    //remove row from items table
                    model.removeRow(jTable1.getSelectedRows()[jTable1.getSelectedRows().length - 1]);
                }

            } else {
                throw new Exception("Please selected row that you want to remove!");
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage(), "Notice", JOptionPane.OK_OPTION);
        }

    }//GEN-LAST:event_btnRemoveActionPerformed

    private void btnRemoveAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveAllActionPerformed
        //remove all items rows
        if (JOptionPane.showConfirmDialog(null, "Are you sure?") == 0) {
            for (int i = model.getRowCount() - 1; i >= 0; i--) {
                model.removeRow(i);
            }
        }
    }//GEN-LAST:event_btnRemoveAllActionPerformed

    private void btnProduceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnProduceActionPerformed
//produce bills
        if (jTable1.getRowCount() > 0) {
            //check for confirmation
            if (JOptionPane.showConfirmDialog(null, "this will save this bill to database, are you sure?", "Confirm", JOptionPane.OK_CANCEL_OPTION) == 0) {
                bh = new BillHandling();
                bdh = new BillDetailHandling();
                try {
                    try {
                        //deleted bills if existed
                        bh.deleteBill(txtBillID.getText());
                    } catch (Exception ex1) {
                        Logger.getLogger(ProduceBillsPanel.class.getName()).log(Level.SEVERE, null, ex1);
                    } finally {
                        //insert bills to database
                        if (bh.insertBill(new Bill(txtBillID.getText(), loginUser, dateString, txtCustomer.getText().trim(), cbPayment.getSelectedItem().toString()))) {
                            for (int i = 0; i < jTable1.getRowCount(); i++) {
                                //insert billdetails to database
                                bdh.insertBillDetail(txtBillID.getText(), (String) model.getValueAt(i, 0), Integer.parseInt(model.getValueAt(i, 4).toString()));

                            }
                            //preview bills
                            preview();
                        }
                    }
                } catch (Exception ex) {
                }
            }
        } else {
            lblError.setText("The table empty, cannot create bill!");
        }

        for (int i = 0; i < jTable1.getRowCount(); i++) {
            try {
                //update items quantity in database
                ih.updateItemQuantity(model.getValueAt(i, 0).toString(), Integer.parseInt(model.getValueAt(i, 4).toString()) - Integer.parseInt(txtQuantity.getText()));
            } catch (Exception ex) {
                Logger.getLogger(ProduceBillsPanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
   }//GEN-LAST:event_btnProduceActionPerformed

    private void jTable1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MousePressed
        // TODO add your handling code here:
        cbItemName.setSelectedItem((String) model.getValueAt(jTable1.getSelectedRow(), 1));
        txtQuantity.setText(String.valueOf(model.getValueAt(jTable1.getSelectedRow(), 4)));
    }//GEN-LAST:event_jTable1MousePressed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        //cancel current bills
        // TODO add your handling code here:
        try {
            //confirmation
            if (JOptionPane.showConfirmDialog(null, "Are you sure?") == 0) {
                //delete current bills
                bh.deleteBill(txtBillID.getText());
                lblError.setText("Cancelling bill was success");
            }
        } catch (Exception ex1) {
            //if the bill is not exist
            lblError.setText("This bill has not created or deleted.");
        }
    }//GEN-LAST:event_btnCancelActionPerformed

    private void btnCancelFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_btnCancelFocusLost
        // TODO add your handling code here:
        lblError.setText("");
    }//GEN-LAST:event_btnCancelFocusLost

    private void txtQuantityFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtQuantityFocusLost
        // TODO add your handling code here:
        //check that the quantity inputted is a number
        if (!txtQuantity.getText().matches("[0-9]+")) {
            txtQuantity.setText("0");
            lblError.setText("Quantity must be a valid number!");
        } else {
            lblError.setText("");
        }
    }//GEN-LAST:event_txtQuantityFocusLost

    private void txtQuantityFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtQuantityFocusGained
        // TODO add your handling code here:

        txtQuantity.setText("");

    }//GEN-LAST:event_txtQuantityFocusGained

    private void txtQuantityActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtQuantityActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtQuantityActionPerformed

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        lblError.setText("");
        try {
            // TODO add your handling code here:
            //check if the field is valid
            if (isValidated()) {
                if (!isExisted(cbItemName.getSelectedItem().toString())) {
                    try {
                        //add item to bills table
                        addToBill();
                    } catch (FileNotFoundException ex) {
                        Logger.getLogger(ProduceBillsPanel.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (IOException ex) {
                        Logger.getLogger(ProduceBillsPanel.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (ClassNotFoundException ex) {
                        Logger.getLogger(ProduceBillsPanel.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } else {
                    lblError.setText("the item has been added, to modify, use 'Edit' button");
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(ProduceBillsPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnAddActionPerformed

    private void txtCustomerFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtCustomerFocusLost
        // TODO add your handling code here:
        //check if the customer name is valid
        if (txtCustomer.getText().trim().length() == 0) {
            lblError.setText("Customer name cannot be empty!");
        } else {
            lblError.setText("");
        }
    }//GEN-LAST:event_txtCustomerFocusLost

    private void txtCustomerFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtCustomerFocusGained

    }//GEN-LAST:event_txtCustomerFocusGained

    private void txtCustomerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCustomerActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCustomerActionPerformed

    private void btnHelpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHelpActionPerformed
        try {
            // TODO add your handling code here:
            //open user guild
            InventoryManagement.OpenManual();
        } catch (IOException ex) {
            lblError.setText("cannot file manual file in 'manual/ISM_Manual.htm'");
        }
    }//GEN-LAST:event_btnHelpActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnEdit;
    private javax.swing.JButton btnHelp;
    private javax.swing.JButton btnNew;
    private javax.swing.JButton btnProduce;
    private javax.swing.JButton btnRemove;
    private javax.swing.JButton btnRemoveAll;
    private javax.swing.JComboBox cbItemName;
    private javax.swing.JComboBox cbPayment;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel21;
    private javax.swing.JLabel jLabel22;
    private javax.swing.JLabel jLabel23;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable jTable1;
    private javax.swing.JToolBar jToolBar7;
    private javax.swing.JLabel lblBanner;
    private javax.swing.JLabel lblDate;
    private javax.swing.JLabel lblError;
    private javax.swing.JLabel lblFullname;
    private javax.swing.JLabel txtBillID;
    private javax.swing.JTextField txtCustomer;
    private javax.swing.JLabel txtDate;
    private javax.swing.JLabel txtFullname;
    private javax.swing.JTextField txtQuantity;
    // End of variables declaration//GEN-END:variables
}
